package csc.fresher_group2.dao;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class Utils {

	public static String convertDateTimeFromLongNumber(long time) {
		String date = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
				.format(new java.util.Date(time));
		return date;
	}

	public static String convertFileSize(long size) {
		if (size <= 0)
			return "0";
		final String[] units = new String[] { "B", "KB", "MB", "GB", "TB" };
		int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
		return new DecimalFormat("#,##0.#").format(size
				/ Math.pow(1024, digitGroups))
				+ " " + units[digitGroups];
	}

	public static byte[] zipFiles(File[] files) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ZipOutputStream zos = new ZipOutputStream(baos);
		
		doZip(files,zos);
		zos.flush();
		baos.flush();
		zos.close();
		baos.close();
		
		return baos.toByteArray();
	}
	
	private static void doZip(File[] files, ZipOutputStream zos){
		try{
			for(int i=0;i<files.length;i++){
				if(files[i].isDirectory()){				
					zos.putNextEntry(new ZipEntry(files[i].getName()));
					doZip(files[i].listFiles(),zos);
					continue;
				}else{
					byte[] buffer = new byte[1024];
					FileInputStream fis = new FileInputStream(files[i]);				
					zos.putNextEntry(new ZipEntry(files[i].getName()));
					int length;
					while((length=fis.read(buffer))>0){
						zos.write(buffer, 0, length);
					}
					zos.flush();
					zos.closeEntry();
					fis.close();
				}
			}
			zos.flush();
			zos.closeEntry();
		}catch(IOException e){
			
		}
	}
	
}
